package com.prex.common.social.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.prex.common.social.entity.GiteeUserInfo;
import com.prex.common.social.config.GiteeConfig;
import com.prex.common.auth.exception.SocialServiceException;
import com.prex.common.social.service.GiteeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Classname GiteeServiceImpl
 * @Description TODO
 * @Author Created by Lihaodong (alias:小东啊) im.lihaodong@gmail.com
 * @Date 2019-09-16 11:39
 * @Version 1.0
 */
@Slf4j
@Service
public class GiteeServiceImpl implements GiteeService {

    /**
     * 获取用户信息
     */
    private static final String URL_GET_USRE_INFO = "https://gitee.com/api/v5/user";

    @Autowired
    private GiteeConfig giteeConfig;

    @Override
    public GiteeUserInfo getUserInfo(String code) {
        try {
            String clientId = giteeConfig.getAppId();
            String clientSecret = giteeConfig.getAppSecret();
            String redirectUri = giteeConfig.getRedirectUri();

            String url = String.format("https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=%s&redirect_uri=%s&client_secret=%s", code, clientId, redirectUri, clientSecret);
            String post = HttpUtil.post(url, "", 5000);
            JSONObject object = JSONObject.parseObject(post);
            String accessToken = (String) object.get("access_token");
            String scope = (String) object.get("scope");
            String refreshToken = (String) object.get("refresh_token");
            int expiresIn = (Integer) object.get("expires_in");
            log.info("获取Toke的响应:{},scope响应:{},refreshToken响应:{},expiresIn响应:{}", accessToken, scope, refreshToken, expiresIn);

            if (accessToken != null && !"".equals(accessToken)) {
                Map<String, Object> user = JSON.parseObject(HttpUtil.get(String.format(URL_GET_USRE_INFO + "?access_token=%s", accessToken), 5000), Map.class);
                if (ObjectUtil.isNotNull(user)) {
                    int id = (int) user.get("id");
                    String username = String.valueOf(user.get("login"));
                    String name = String.valueOf(user.get("name"));
                    String avatarUrl = user.get("avatar_url") != null ? String.valueOf(user.get("avatar_url")) : null;
                    String url1 = String.valueOf(user.get("url"));
                    String htmlUrl = String.valueOf(user.get("html_url"));
                    String followersUrl = String.valueOf(user.get("followers_url"));
                    String followingUrl = String.valueOf(user.get("following_url"));
                    String blog = user.get("blog") != null ? String.valueOf(user.get("blog")) : null;
                    GiteeUserInfo userInfo = GiteeUserInfo.builder()
                            .id(id)
                            .login(username)
                            .name(name)
                            .avatarUrl(avatarUrl)
                            .url(url1)
                            .htmlUrl(htmlUrl)
                            .followersUrl(followersUrl)
                            .followingUrl(followingUrl)
                            .blog(blog)
                            .build();
                    log.info("Gitee userInfo : [{}]", userInfo);
                    return userInfo;
                }
            }
        } catch (Exception e) {
            log.error("码云登录信息错误,{}", e.getLocalizedMessage());
        }
        throw new SocialServiceException("码云登录信息错误",null);
    }
}
